﻿using System.Reflection;
using FireChat.Share.Web.Actions;

namespace FireChat.Share.Web.Util;


/// <summary>
/// 数据包脚手架
/// </summary>
public static class ActionScaffold<T> where T : IAction
{
    /// <summary>
    /// 所有动作列表
    /// </summary>
    private static readonly List<T> _actions = new();

    /// <summary>
    /// 所有动作
    /// </summary>
    public static IEnumerable<T> Actions => _actions;


    static ActionScaffold()
    {
        var types = Assembly.GetEntryAssembly()?.GetTypes() ?? Array.Empty<Type>();

        List<T> actions = new();

        foreach (var i in types)
        {
            if (i.IsInterface || i.IsAbstract) continue;


            if (i.IsAssignableTo(typeof(T)))
            {
                if (Activator.CreateInstance(i) is not T action) continue;

                actions.Add(action);
            }
            else if (i.IsAssignableTo(typeof(T)))
            {
                if (Activator.CreateInstance(i) is not T @event) continue;

                actions.Add(@event);
            }
        }

        _actions = actions;
    }
}